import { load } from "protobufjs";
import fs from "fs";
import path from "path";
import { ensureDir, log } from "./utils";
const protoDirPath = path.join(__dirname, "../proto");
const dataDirPath = path.join(__dirname, "../data");
const outputDirPath = path.join(__dirname, "../binary");
const protoFilePaths = fs.readdirSync(protoDirPath);
ensureDir(outputDirPath);
protoFilePaths.forEach(async (pfp, index) => {
  console.log(`----- ${index + 1} of ${protoFilePaths.length} -----`);
  const name = path.parse(pfp).name;
  await load(path.join(protoDirPath, pfp))
    .then((root) => {
      const type = root.lookupType(name);
      const data = JSON.parse(
        fs.readFileSync(path.join(dataDirPath, name + ".json"), {
          encoding: "utf-8",
        })
      );
      const err = type.verify(data);
      if (err) {
        log(name, err);
        return;
      }
      const msg = type.create(data);
      const buffer = type.encode(msg).finish();
      console.log(`output size: ${buffer.length / 1024} KiB\n\n`);
      fs.writeFileSync(path.join(outputDirPath, name), buffer);
    })
    .catch((err) => {
      log(name, err);
    });
});
